package com.atguigu.guli.service.sms.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.sms.service.SmsService;
import com.atguigu.guli.service.sms.util.SmsProperties;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService{

    @Autowired
    private SmsProperties smsProperties;

    @Override //发送短信
    public void sendSms(String mobile, String checkCode) {

        //创建客户端对象
        DefaultProfile profile = DefaultProfile.getProfile(

                smsProperties.getRegionId(),
                smsProperties.getKeyId(),
                smsProperties.getKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);


        //创建远程链接的请求参数
        //创建远程连接的请求参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", smsProperties.getRegionId());
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", smsProperties.getSignName());
        request.putQueryParameter("TemplateCode", smsProperties.getTemplateCode());

        //组装JSON数据
        Gson gson = new Gson();//模板用gson封装
       Map<String, String> map = new HashMap<>();//存储键值对
       map.put("code",checkCode); //checkCode 验证码
       String json = gson.toJson(map);//转换成json对象，得到json字符串
       request.putQueryParameter("TemplateParam",json);

       //使用客户端对象携带请求对象发送请求并得到响应结果
        CommonResponse response = null;
        try {
            //调用CommonResponse方法，把request请求发送出去
           response = client.getCommonResponse(request);

        //得到响应数据
        String data = response.getData();
        //响应是字符串类型，将数据转换为字符串
        HashMap<String, String> resultMap = gson.fromJson(data, HashMap.class);
        String code = resultMap.get("Code");
        String message = resultMap.get("Message");

        if ("isv.BUSINESS_LIMIT_CONTROL".equals(code)){
            log.error("短信发送过于频繁：code =" + code + ", message =" + message);
            throw new GuliException(ResultCodeEnum.SMS_SEND_ERROR_BUSINESS_LIMIT_CONTROL);
        }

        //发送失败，错误日志（给开发者或运营人员观看）
        if (!"OK".equals(code)){
            log.error("短信发送失败：code =" + code + ", message =" + message);
            throw new GuliException(ResultCodeEnum.SMS_SEND_ERROR);
            }

        } catch (ClientException e) {
            log.error("短信发送失败："+ ExceptionUtils.getStackTrace(e));
        }
    }
}
